package com.quyl.poi.service;


import cn.hutool.json.JSONUtil;
import com.quyl.poi.util.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

@Service
public class PoiExcelService {
    private static final Logger logger = LoggerFactory.getLogger(PoiExcelService.class);

    public List<Map<String, Object>> callableTask(String path) throws ExecutionException, InterruptedException {
        //读取单个文件
        // 开始时间
        long stime = System.currentTimeMillis();
        // 执行
        logger.info("------开始解析-------");
        File file = new File(path);
        File[] files = file.listFiles();
        List<Map<String, Object>> listRes = new ArrayList<>();
        ThreadPoolExecutor pool = new ThreadPoolExecutor(Constant.CONSTANT_8, 12, 1, TimeUnit.SECONDS, new LinkedBlockingQueue());
        if (files == null || files.length <= 0) {
            logger.info("未获取到数据模型excel文件。");
            return null;
        }
        List<Future> list = new ArrayList<>();
        Future submit;
        for (File fileItem : files) {
            submit = pool.submit(new ExcelCallable(fileItem.getPath()));
            list.add(submit);
        }
        pool.shutdown();
        int length = list.toArray().length;
        for (int i = 0; i < length; i++) {
            Future future = list.get(i);
            while (!future.isDone()) ; //
            listRes.add((Map<String, Object>) future.get());
            //解析后计算执行百分比
//            ProcessBarUtil.printCurrentNum(((i + 1) * 100) / length, i + 1, length);
        }
        logger.debug(JSONUtil.toJsonStr(listRes));
        // 计算执行时间
        // 结束时间
        long etime = System.currentTimeMillis();
        System.out.println();
        logger.info("执行时长：{} 秒.", (etime - stime) / 1000);
        return listRes;
    }

}
